package com.example.administrator.hqq.activity.group;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.alertview.OnItemClickListener;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class CreateGroupChatActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.groud_pic)
    ImageView groudPic;
    @BindView(R.id.group_name)
    EditText groupName;
    @BindView(R.id.skip_activity)
    TextView skipActivity;
    @BindView(R.id.skip_activity_auto)
    RelativeLayout skipActivityAuto;
    @BindView(R.id.group_add)
    AutoLinearLayout groupAdd;
    private String url = "";
    private String name = "";
    private String TAG = this.getClass().getSimpleName();
    private QNTokenBean qnTokenBean;
    private String groupId;
    private AlertView photoAlertView;
    private AlertView photoTypeAlertView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group_chat);
        ButterKnife.bind(this);
        initview();
        initData();
    }

    private void initview() {
        SketchTextWatcher sketchTextWatcher = new SketchTextWatcher(groupName, 54);
        groupName.addTextChangedListener(sketchTextWatcher);
    }

    private void initData() {
        OkHttpUtils.get().url(UrlFactory.getGROUPPrepare_add())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "准备设置群聊onError: "+e );
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: "+response );
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code)==200)
                    {
                        groupId = jsonObject.getString(LoongsConfig.group_id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                getQNToken(path);
//                File picFile = new File(path);
//                if (picFile.exists()) {
//                    CameraUtils.getInstance().cropPicture(CreateGroupChatActivity.this, path, 3, 3);//裁剪图片
//                }
            }

            @Override
            public void selectPictureFinish(String path) {
                getQNToken(path);
//                File picFile = new File(path);
//                if (picFile.exists()) {
//                    CameraUtils.getInstance().cropPicture(CreateGroupChatActivity.this, path, 3, 3);//裁剪图片
//                }
            }

            @Override
            public void cropPictureFinish(String path) {

            }
        });
    }

    public void getQNToken(String path) {
        showLoadingDialog();
        final File picFile = new File(path);
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.id, groupId)
                .addParams(LoongsConfig.type, LoongsConfig.GROUP)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "onResponse: " + s);
                final Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "res");
                                groupAdd.setVisibility(View.GONE);
                                Glide.with(CreateGroupChatActivity.this.getApplicationContext())
                                        .load(qnTokenBean.getUrl())
                                        .centerCrop()
                                        .into(groudPic);
                                url = qnTokenBean.getId();
                            } else {

                            }
                            dismissLoadingDialog();
                            Log.e("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
            }
        });
    }
    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CreateGroupChatActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnClick({R.id.return_auto, R.id.groud_pic, R.id.skip_activity_auto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.groud_pic:
                //        CreateGroupChatActivityPermissionsDispatcher.startStorageWithCheck(CreateGroupChatActivity.this);
                photoAlertView = AlertViewFactory.getInstance().getPhotoAlertView(this, new OnItemClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1) {
                            photoAlertView.dismiss();
                        } else if (position == 2) {
                            url = "system_group_v1";
                            groupAdd.setVisibility(View.GONE);
                            Glide.with(CreateGroupChatActivity.this.getApplicationContext())
                                    .load(R.drawable.system_group_v1)
                                    .centerCrop()
                                    .into(groudPic);
                        } else if (position == 0) {
                            CreateGroupChatActivityPermissionsDispatcher.startLocationWithCheck(CreateGroupChatActivity.this);
                        } else if (position == 1) {
                            CreateGroupChatActivityPermissionsDispatcher.startStorageWithCheck(CreateGroupChatActivity.this);
                        }
                    }
                });
                photoAlertView.show();
                break;
            case R.id.skip_activity_auto:
                name = groupName.getText().toString();
                if (TextUtils.isEmpty(url)) {
                    Toast.makeText(this, "请选择用户头像", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (TextUtils.isEmpty(name)||name.length()<2) {
                        Toast.makeText(this, "群昵称输入不正确", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        if (MyTextUtils.isEmptyString(groupName)){
                            ToastUtils.showShort("群标题不能全是空格");
                            return;
                        }
                        if (!TextUtils.isEmpty(groupId))
                        {
                            Intent intent = new Intent(CreateGroupChatActivity.this, SelectNumbeActivity.class);
                            intent.putExtra(LoongsConfig.title, name);
                            intent.putExtra(LoongsConfig.url, url);
                            intent.putExtra(LoongsConfig.topic_id,getIntent().getStringExtra(LoongsConfig.topic_id));
                            intent.putExtra(LoongsConfig.group_id,groupId);
                            startActivity(intent);
                        }
                        else{
                            ToastUtils.showShort("请稍后重试");
                        }
                    }
                }
                break;
            default:
        }
    }

    public void getPhotoTypeAlertView() {
        photoTypeAlertView = AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    photoTypeAlertView.dismiss();
                } else if (position == 0) {
                    CreateGroupChatActivityPermissionsDispatcher.startLocationWithCheck(CreateGroupChatActivity.this);
                } else if (position == 1) {
                    CreateGroupChatActivityPermissionsDispatcher.startStorageWithCheck(CreateGroupChatActivity.this);
                }
            }
        });
        photoTypeAlertView.show();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
